﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CubicFWNet.Application.SystemManager;
using CubicFWNet.Common;
using CubicFWNet.Data.Models;
using CubicFWNet.Data.ViewModal;
using PagedList;

namespace CubicFWNet.Mvc.Controllers
{
    public class ExamineController : ControllerBase
    {
        private ExamineApp _examineApp;
        private PurchaseApp _purchaseApp;
        private WorksheetApp _worksheetApp;
        private OrderProductApp _orderProductApp;
        private TechnologyApp _technologyApp;
        private OperateRecordApp _operateRecordApp;
        private StorageTableApp _storageTableApp;


        public ExamineController()
        {
            _examineApp = new ExamineApp();
            _purchaseApp = new PurchaseApp();
            _worksheetApp = new WorksheetApp();
            _orderProductApp = new OrderProductApp();
            _technologyApp = new TechnologyApp();
            _operateRecordApp = new OperateRecordApp();
            _storageTableApp = new StorageTableApp();
        }

        // GET: Examine
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CheckOtherProductIng(int page = 1, string productName = "")
        {

            return View();
        }

        public ActionResult Check(int page = 1, string productName = "", string beginTime = "", string endTime = "")
        {
            ViewBag.productName = productName.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _examineApp.GetList(-1, productName, _beginTime, _endTime).ToPagedList(page, 10);
            return View(tecjList);
        }

        public ActionResult CheckFinish(int page = 1, string productName = "", string beginTime = "", string endTime = "")
        {
            ViewBag.productName = productName.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _examineApp.GetList(1, productName, _beginTime, _endTime).ToPagedList(page, 10);
            return View(tecjList);
        }

        public ActionResult CheckInfo(Guid tId)
        {
            Examine exa = _examineApp.GetSinglExamine(tId);
            Guid orderId = Guid.Empty;
            int type = 1;
            int examinetype = exa.Type;
            decimal amount = 0;
            User u = _orderProductApp.GetSinleUserById(exa.ApplyId.Value);
            Product pro = new Product();
            TechType techType = new TechType();
            decimal checkLong = 0;
            //采购
            if (exa.Type == 1 && exa.ItemId != null)
            {
                PurchaseCompose p = _purchaseApp.GetSinglePurchaseComposeById(exa.ItemId.Value);
                amount = p.Amount;
                pro = _technologyApp.GetSingleProduct(p.ProductId);
                //type = pro.Type;
                orderId = pro.Id;
                Relation relation = _technologyApp.GetListRelation(p.Id, "PurchaseCompose-Purchase").FirstOrDefault();
                if (relation != null && relation.SecondId != null)
                {
                    ProductTechnologyView pvObj = _technologyApp.GetRelationProductList(relation.SecondId.Value, pro.Id);
                    if (pvObj != null)
                    {
                        checkLong = pvObj.CheckLenth;
                    }
                }

                //订单产品外购
                //if (p.Type == 1)
                //{
                //OrderProduct op = _orderProductApp.GetSingleOrderProductBypurId(p.Id);

                //orderId = op.OrderId.Value;
                //}
                //.自定义采购
                //if (p.Type == 2 || p.Type == 3)
                //{
                //    pro = _technologyApp.GetSingleProduct(p.ProductId);
                //    type = pro.Type;
                //}
            }
            //生产检验
            if (exa.Type == 2 && exa.ItemId != null)
            {
                Worksheet w = _worksheetApp.GetSingleWorksheet(exa.ItemId.Value);
                pro = _technologyApp.GetSingleProduct(w.ProductId);
                //type = pro.Type;
                amount = w.WorkAmount;
                orderId = pro.Id;
                Technology t = null;
                OrderProduct op = null;
                if (w.TechnologyId != null)
                {
                    t = _technologyApp.GetSingleTechnology(w.TechnologyId.Value);
                }
                else
                {
                    op = _orderProductApp.GetSingleOrderProductById(tId);//查找第一次
                    if (op == null && w.ParentId != null)
                    {
                        op = _orderProductApp.GetSingleOrderProductById(w.ParentId.Value);//查找第二次
                        if (op == null)
                        {
                            Worksheet tempw = _worksheetApp.GetSingleWorksheet(w.ParentId.Value);
                            if (tempw != null && tempw.ParentId != null && tempw.Type == 2)
                            {
                                op = _orderProductApp.GetSingleOrderProductById(tempw.ParentId.Value);//查找第三次
                            }
                        }
                    }
                    if (op != null)
                    {
                        if (op.PrimaryID != null)
                        {
                            t = _technologyApp.GetSingleTechnologyById(op.PrimaryID.Value);
                        }
                        else
                        {
                            t = _technologyApp.GetSingleTechnologyById(op.Id);
                        }
                    }
                }

                if (t != null)
                {
                    checkLong = t.CheckLenth;
                }
            }

            #region 查找对应的工艺
            TechnologyManageView tmweb = _technologyApp.GetTechnologyManageSingle(pro.Id);
            Equipment equipment = _technologyApp.GetSingleEquipment(tmweb.EquipmentType);
            techType = _technologyApp.GetSingleTechType(equipment.Id, tmweb.TechType);
            #endregion

            ViewBag.TechType = techType;
            ViewBag.CheckToalLength = checkLong;
            ViewBag.Product = pro;
            ViewBag.OrderId = orderId;
            //ViewBag.Type = type == 1 ? "产品" : "原材料";
            ViewBag.Examinetype = examinetype == 1 ? "采购" : "生产检验";
            ViewBag.ApplyName = u.RealName;
            ViewBag.Amount = amount;

            string shortName = operatorModel.FamilyName;
            ViewBag.ExamineNum = shortName + "-" + GenerateId.GenerateOrderNumber();//生成检验编号
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            return View(exa);
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string CompleteExamine(Examine web, Guid purchaseNameId, string orderNumber)
        {
            DateTime nowTime = DateTime.Now;
            Examine exa = _examineApp.GetSinglExamine(web.Id);
            exa.CreatorId = operatorModel.UserId;
            exa.CreatorName = operatorModel.FamilyName;
            exa.CreateTime = nowTime;
            exa.Status = 1;
            exa.Memo = web.Memo;
            exa.Number = web.Number;
            exa.ProducAmount = web.ProducAmount;
            exa.StandardAmount = web.StandardAmount;
            exa.Unit = web.Unit;
            exa.RealExamLength = web.RealExamLength;
            _examineApp.Update(exa);//修改检验单

            OperateRecord o = new OperateRecord();
            o.ItemId = web.Id;
            o.TypeId = 15;
            o.EndTime = nowTime;
            o.CreatorId = operatorModel.UserId;
            o.CreatorName = operatorModel.FamilyName;
            _operateRecordApp.UpdateOperateRecord(o);//修改本操作人员工作记录日志

            Product pro = _technologyApp.GetSingleProduct(purchaseNameId);
            if (web.StandardAmount > 0)
            {
                StorageTable e = new StorageTable();//插入库房表
                Guid newId = Guid.NewGuid();
                e.Id = newId;
                //e.Status = -1;
                e.Type = 2;
                e.OrderNumber = orderNumber;
                e.ProductId = purchaseNameId;
                //e.Format = pro.Format;
                //e.Unit = pro.Unit;
                e.Amount = web.StandardAmount;
                //e.ApplyTime = nowTime;
                //e.CreatorId = null;
                e.CreateTime = DateTime.Now;
                //e.ApplyId = operatorModel.UserId;
                //e.OtherId = exa.ItemId;
                e.OtherType = exa.Type;
                _storageTableApp.Add(e);

                //插入关系表
                Relation re = new Relation();
                re.Id = Guid.NewGuid();
                re.TypeId = "StorageTable-Examine";
                re.FirstId = newId;
                re.SecondId = exa.Id;
                _technologyApp.InsertRelation(re);

                //插入给下一个工作人员添加人工记录
                OperateRecord o1 = new OperateRecord();
                o1.Id = Guid.NewGuid();
                o1.ItemId = newId;//工单id
                o1.TypeId = 21;
                o1.StartTime = nowTime;
                o1.EndTime = null;
                o1.CreatorId = null;
                _operateRecordApp.AddOperateRecord(o1);

            }

            //采购
            if (exa.Type == 1)
            {
                //修改合成采购表的“合格数量”字段
                PurchaseCompose p = _purchaseApp.GetSinglePurchaseComposeById(exa.ItemId.Value);
                //decimal agoStandardAmount = p.StandardAmount;
                decimal nowStandardAmount = p.StandardAmount + web.StandardAmount;
                p.StandardAmount = nowStandardAmount;
                if (p.ParentId != null)//说明是补单,不看数量每次都修改状态
                {
                    p.Status = 10;
                }
                if (p.ParentId == null && (p.Amount <= nowStandardAmount))//不是补单，一次审核通过
                {
                    p.Status = 10;
                }
                _purchaseApp.UpdatePurchaseCompose(p);


                /*#region 给采购对账插入
                PurchaseReconciliation pr = new PurchaseReconciliation();
                Guid newId = Guid.NewGuid();
                pr.Id = newId;
                pr.PurchaseComposeId = p.Id;
                pr.Status = -1;
                pr.ApplyTime = nowTime;
                pr.ShouldAmount = p.Amount;
                pr.ActualAmount = web.StandardAmount;
                pr.FinanceNumber = "";
                _purchaseApp.AddPurchaseReconciliation(pr);

                //插入给下一个工作人员添加人工记录
                OperateRecord o1 = new OperateRecord();
                o1.Id = Guid.NewGuid();
                o1.ItemId = newId;//Id
                o1.TypeId = 23;
                o1.StartTime = nowTime;
                o1.EndTime = null;
                o1.CreatorId = null;
                _operateRecordApp.AddOperateRecord(o1);
                #endregion*/

                if (p.ParentId != null)
                {
                    PurchaseCompose supweb = _purchaseApp.GetSinglePurchaseComposeById(p.ParentId.Value);
                    if (supweb != null)
                    {
                        supweb.StandardAmount = supweb.StandardAmount + web.StandardAmount;
                        if (supweb.Amount <= supweb.StandardAmount)
                        {
                            supweb.Status = 10;

                            //修改Purchase对应的所有OrderProduct状态
                            List<Relation> relationList = _technologyApp.GetListRelation(supweb.Id, "PurchaseCompose-Purchase");
                            foreach (var item in relationList)
                            {
                                if (item.SecondId != null)
                                {
                                    OrderProduct op = _orderProductApp.GetSingleOrderProductBypurId(item.SecondId.Value);
                                    op.Progress = 11;
                                    _orderProductApp.Update(op);
                                }
                            }
                        }
                        _purchaseApp.UpdatePurchaseCompose(supweb);
                    }
                }

            }
            //生产
            if (exa.Type == 2)
            {
                Worksheet w = _worksheetApp.GetSingleWorksheet(exa.ItemId.Value);
                if (w != null)
                {
                    w.Status = 2;
                    w.StandardAmount = w.StandardAmount + web.StandardAmount;
                    if (w.Type == 1)//补单生产，没次审核都修改
                    {
                        w.ExamineStatus = 1;
                    }
                    if ((w.Type == 0 || w.Type == 2) && (w.WorkAmount <= w.StandardAmount))//正常生产 或者 分批生产
                    {
                        //修改OrderProduct工作进度
                        OrderProduct op = _orderProductApp.GetSingleOrderProductById(w.Id);
                        if (op == null && w.ParentId != null)
                        {
                            op = _orderProductApp.GetSingleOrderProductById(w.ParentId.Value);
                        }
                        if (op != null)
                        {
                            op.Progress = 11;
                            _orderProductApp.Update(op);
                        }

                        w.ExamineStatus = 1;
                    }
                    _worksheetApp.Update(w);//完善修改生成订单信息

                    //说明有上级加工单
                    if (w.ParentId != null && w.Type == 1)
                    {
                        Worksheet parework = _worksheetApp.GetSingleWorksheet(w.ParentId.Value);
                        if (parework != null)
                        {
                            parework.StandardAmount = parework.StandardAmount + web.StandardAmount;
                            if (parework.WorkAmount <= parework.StandardAmount)
                            {
                                //修改OrderProduct工作进度
                                OrderProduct op = _orderProductApp.GetSingleOrderProductById(parework.Id);
                                if (op == null && parework.ParentId != null)
                                {
                                    op = _orderProductApp.GetSingleOrderProductById(parework.ParentId.Value);
                                }
                                if (op != null)
                                {
                                    op.Progress = 11;
                                    _orderProductApp.Update(op);
                                }
                                parework.ExamineStatus = 1;
                                w.ExamineStatus = 1;
                            }
                            _worksheetApp.Update(parework);//修改最上级的合格数量（累加）
                        }
                    }
                }
            }
            //_operateRecordApp.UpdateOrderStateById(orderId, 10);//更改订单Status=10

            return Result.ToJson();
        }

        public ActionResult Query()
        {
            return View();
        }

        public ActionResult QueryInfo()
        {
            return View();
        }

        public ActionResult GradeMaintenanceJy()
        {
            List<GradeMaintenance> gmList = _technologyApp.GetListGradeMaintenance(1);
            return View(gmList);
        }


        [HttpPost]
        [HandlerAjaxOnly]
        public string AddOrUpdateGradeMaintenance(GradeMaintenance gGradeMaintenance, string sign)
        {
            if (gGradeMaintenance.Data != null)
            {
                List<GradeMaintenance> gmList = Common.Json.ToObject<List<GradeMaintenance>>(gGradeMaintenance.Data);
                //修改
                if (sign == "1")
                {
                    foreach (var item in gmList)
                    {
                        GradeMaintenance web = _technologyApp.GetSingleGradeMaintenance(item.Id);
                        web.Num = item.Num;
                        _technologyApp.UpdateGradeMaintenance(web);
                    }
                }
                //添加
                if (sign == "-1")
                {
                    foreach (var item in gmList)
                    {
                        item.Id = Guid.NewGuid();
                        _technologyApp.InsertGradeMaintenance(item);
                    }
                    //_technologyApp.InsertGradeMaintenanceBatch(gmList);
                }
            }
            return Result.ToJson();
        }
    }
}